<template>
  <div>

    <div class="card" style="margin-bottom: 10px;">
      餐品名称：<el-input v-model="data.params.productName" style="width: 180px; margin-right: 10px" placeholder="请输入餐品名称查询"></el-input>
      查询餐品价格不超过：<el-input v-model="data.params.productPrice" style="width: 180px; margin-right: 10px" placeholder="请输入餐品价格查询" type="number"></el-input>
      餐品类别：<el-select v-model="data.params.categoryType" style="width: 140px; margin-right: 10px" placeholder="请选择类别">
        <el-option label="全部" value=""></el-option>
        <el-option
          v-for="item in data.categoryOptions"
          :key="item.categoryType"
          :label="item.categoryName"
          :value="item.categoryId">
        </el-option>
      </el-select>
      餐品状态：<el-select v-model="data.params.productStatus" style="width: 140px; margin-right: 10px" placeholder="请选择状态">
        <el-option label="全部" value=""></el-option>
        <el-option label="正常" value="0"></el-option>
        <el-option label="下架" value="1"></el-option>
      </el-select>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 10px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table stripe :data="data.tableData">
        <el-table-column label="餐品ID" prop="productId" width="80px"></el-table-column>
        <el-table-column label="餐品图片" width="140px">
          <template #default="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.productIcon"
              fit="cover"
              :preview-src-list="[scope.row.productIcon]"
              :preview-teleported="true"
              :z-index="999999"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="餐品名称" prop="productName" width="160px"></el-table-column>
        <el-table-column label="餐品价格" prop="productPrice" width="120px">
          <template #default="scope">
            <span>{{ scope.row.productPrice ? '¥' + scope.row.productPrice.toFixed(2) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="餐品库存" prop="productStock" width="110px"></el-table-column>
        <el-table-column label="所属类别" prop="categoryName" width="110px"></el-table-column>
        <el-table-column label="餐品状态" width="120px">
          <template #default="scope">
            <el-tag :type="scope.row.productStatus === 0 ? 'success' : 'danger'">{{ scope.row.productStatus === 0 ? '正常' : '下架' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="餐品描述" prop="productDescription"></el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.productId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="data.params.pageSize"
        v-model:current-page="data.params.pageNum"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog title="餐品信息" width="50%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="餐品名称" prop="productName">
          <el-input v-model="data.form.productName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="餐品价格" prop="productPrice">
          <el-input v-model="data.form.productPrice" autocomplete="off" type="number" />
        </el-form-item>
        <el-form-item label="餐品库存" prop="productStock">
          <el-input v-model="data.form.productStock" autocomplete="off" type="number" />
        </el-form-item>
        <el-form-item label="所属类别" prop="categoryType">
          <el-select v-model="data.form.categoryId" placeholder="请选择类别">
            <el-option
              v-for="item in data.categoryOptions"
              :key="item.categoryType"
              :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐品状态" prop="productStatus">
          <el-radio-group v-model="data.form.productStatus">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="餐品描述" prop="productDescription">
          <el-input v-model="data.form.productDescription" autocomplete="off" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="餐品图片" prop="productIcon">
          <el-upload
            class="avatar-uploader"
            action="/api/files/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess">
            <img v-if="data.form.productIcon" :src="data.form.productIcon" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <!-- <div style="color: #999; font-size: 12px; margin-top: 5px">建议上传尺寸为 300x300 的图片</div> -->
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive, onMounted, ref} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import { Plus } from '@element-plus/icons-vue';

const data = reactive({
  params: {
    productName: '',
    productPrice: '',
    categoryType: '',
    productStatus: '',
    pageNum: 1,
    pageSize: 5
  },
  total: 0,
  formVisible: false,
  form: {},
  tableData: [],
  categoryOptions: []
})

// 加载餐品数据
const load = () => {
  request.get('/seller/productInfo/pageWithCategoryName', {
    params: data.params
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list || []
      data.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载数据失败')
    }
  }).catch(err => {
    console.error('请求出错:', err)
    ElMessage.error('网络请求失败，请检查接口是否可用')
  })
}

// 加载类别数据
const loadCategories = () => {
  request.get('seller/productCategory/list').then(res => {
    if (res.code === '200') {
      data.categoryOptions = res.data || []
    } else {
      ElMessage.error(res.msg || '加载类别数据失败')
    }
  })
}

// 重置查询条件
const reset = () => {
  data.params.productName = ''
  data.params.productPrice = ''
  data.params.categoryType = ''
  data.params.productStatus = ''
  load()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  data.params.pageSize = size
  load()
}

// 处理页码变化
const handleCurrentChange = (current) => {
  data.params.pageNum = current
  load()
}

// 新增餐品
const handleAdd = () => {
  data.form = {productStatus: '0'}
  data.formVisible = true
}

// 编辑餐品
const handleEdit = (row) => {
  //当用户点击编辑按钮时，会将当前行的数据深拷贝到 data.form 中
  data.form = JSON.parse(JSON.stringify(row))
  // 处理类别字段映射：将 categoryId 赋值给表单的 categoryId 字段
  data.form.categoryId = row.categoryId || row.categoryType
  // 处理状态字段映射：将数字类型转换为字符串类型以匹配 radio 的值
  data.form.productStatus = String(row.productStatus || '0')
  data.formVisible = true
}

// 上传图片前的验证
// const beforeUpload = (file) => {
//   const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
//   const isLt2M = file.size / 1024 / 1024 < 2

//   if (!isJPG) {
//     ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
//   }
//   if (!isLt2M) {
//     ElMessage.error('上传图片大小不能超过 2MB!')
//   }
//   return isJPG && isLt2M
// }

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === '200') {
    data.form.productIcon = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

// 保存餐品
const save = () => {
  if (!data.form.productName) {
    ElMessage.warning('请输入餐品名称')
    return
  }
  if (!data.form.productPrice) {
    ElMessage.warning('请输入餐品价格')
    return
  }
  if (!data.form.categoryId) {
    ElMessage.warning('请选择所属类别')
    return
  }
  // if (!data.form.productIcon) {
  //   ElMessage.warning('请上传餐品图片')
  //   return
  // }

  // 将categoryId的值赋给categoryType,因为后端需要categoryType字段
  data.form.categoryType = data.form.categoryId

  const url = data.form.productId ? '/seller/productInfo/update' : '/seller/productInfo/add'
  const method = data.form.productId ? 'put' : 'post'

  request[method](url, data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('保存成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  })
}

// 删除餐品
const handleDelete = (id) => {
  if (!id) return

  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(() => {
    request.delete(`/seller/productInfo/delete/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除操作
  })
}

// 页面加载时获取数据
onMounted(() => {
  load()
  loadCategories()
  // 使用模拟数据，确保界面上有数据显示
  // setTimeout(addMockData, 1000)
})
</script>

<style>
/* 全局样式覆盖，确保预览图片显示在最上层 */
.el-image-viewer__wrapper {
  z-index: 99999 !important;
}

.card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>